package com.hangzhou.xyj.db;

import android.content.Context;

import com.hangzhou.xyj.model.MessageModel;
import com.hangzhou.xyj.model.type.EMessageStatus;
import com.hangzhou.xyj.utils.StringUtil;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;

import java.sql.SQLException;
import java.util.Comparator;
import java.util.List;

/**
 * 关于消息数据库操作
 */
public class MessageDao {
    private Dao<MessageModel, Integer> mDao;
    private DataHelper mHelper = null;

    public MessageDao(Context context) {
        this.mHelper = OpenHelperManager.getHelper(context, DataHelper.class);
        try {
            this.mDao = mHelper.getDao(MessageModel.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    /**
     * 添加消息入库
     *
     * @param msg
     */
    public void addMessage(MessageModel msg) {
        if (msg != null) {
            try {
                mDao.create(msg);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 删除指定id的消息记�?
     *
     * @param id
     */
    public void deleteMessage(int id) {
        try {
            DeleteBuilder<MessageModel, Integer> builder = mDao.deleteBuilder();
            builder.where().eq(MessageModel._ID, id);
            builder.delete();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取�?��消息
     *
     * @return
     */
    public List<MessageModel> getMessagesByType(String uid, int msgType) {
        if (StringUtil.isBlank(uid))
            return null;

        List<MessageModel> msgs = null;

        try {
            QueryBuilder<MessageModel, Integer> builder = mDao.queryBuilder().orderBy(MessageModel.INSERT_TIME, false);
            builder.where()
                    .eq(MessageModel.UID, uid).and().eq(MessageModel.TYPE, msgType);
            msgs = builder.query();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return msgs;
    }

    /**
     * 根据消息类型获取全部消息
     *
     * @param msgType
     * @return
     */
    public List<MessageModel> getAllMessageByType(int msgType) {
        List<MessageModel> msgs = null;

        try {
            QueryBuilder<MessageModel, Integer> builder = mDao.queryBuilder()
                    .orderBy(MessageModel.INSERT_TIME, false);
            builder.where().eq(MessageModel.TYPE, msgType);
            msgs = builder.query();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return msgs;
    }

//    public List<Message> getMessagesByCategory(String uid, int msgCategory){
//		List<Message> allMsgList = new ArrayList<Message>();
//		List<EPushMessageType> categoryList = JMiPushMessageUtil
//				.getMessageTypeByCategory(msgCategory);
//		for (EPushMessageType msgType : categoryList) {
//			List<Message> msgTypeList = getMessagesByType(uid,
//					msgType.getValue());
//			if (msgTypeList != null && msgTypeList.size() > 0) {
//				allMsgList.addAll(msgTypeList);
//			}
//		}
//		//按时间排序消息数�?
//		Collections.sort(allMsgList, new TimeComparator());
//		return allMsgList;
//    }


    /**
     * 获取未读消息条数
     *
     * @return
     */
    public long getUnShownCount(String uid) {
        if (StringUtil.isBlank(uid))
            return 0;

        long count = 0;
        try {
            QueryBuilder<MessageModel, Integer> builder = mDao.queryBuilder();
            builder.where()
                    .eq(MessageModel.UID, uid)
                    .and()
                    .eq(MessageModel.DATA3, EMessageStatus.MESSAGE_STATUS_UN_SHOWN.getValue());
            count = builder.countOf();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return count;
    }


    /**
     * 将所有未读消息置为已�?
     */
    public void setMsgsRead(String uid) {
        if (StringUtil.isBlank(uid))
            return;

        try {
            UpdateBuilder<MessageModel, Integer> builder = mDao.updateBuilder();
            builder.updateColumnValue(MessageModel.STATUS, EMessageStatus.MESSAGE_STATUS_READ.getValue());
            builder.where().eq(MessageModel.UID, uid).and().eq(MessageModel.STATUS, EMessageStatus.MESSAGE_STATUS_UNREAD.getValue());
            builder.update();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    /**
     * 标记消息为已显示
     */
//    public void setMsgsHavaShown(String uid, int msgCategory){
//    	if (StringUtil.isBlank(uid))
//            return;
//        List<EPushMessageType> msgTypeList = JMiPushMessageUtil.getMessageTypeByCategory(msgCategory);
//        for (EPushMessageType msgType : msgTypeList){
//        	try {
//        		UpdateBuilder<Message, Integer> builder = mDao.updateBuilder();
//        		builder.updateColumnValue(Message.DATA3, EMessageStatus.MESSAGE_STATUS_HAVA_SHOWN.getValue());
//        		builder.where().eq(Message.UID, uid).and().eq(Message.DATA3, EMessageStatus.MESSAGE_STATUS_UN_SHOWN.getValue())
//        		.and().eq(Message.TYPE, msgType.getValue());
//        		builder.update();
//        	} catch (SQLException e) {
//        		e.printStackTrace();
//        	}
//        }
//
//    }

    /**
     * 置某个消息为已读状�?
     *
     * @param _id
     */
    public void setMsgReadById(int _id) {
        if (StringUtil.isBlank(String.valueOf(_id)))
            return;

        try {
            UpdateBuilder<MessageModel, Integer> builder = mDao.updateBuilder();
            builder.updateColumnValue(MessageModel.STATUS, EMessageStatus.MESSAGE_STATUS_READ.getValue());
            builder.where().eq(MessageModel._ID, _id);
            builder.update();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据消息类型查询未读数量
     *
     * @param uid
     * @param msgType
     * @return
     */
    public long getUnShownByType(String uid, int msgType) {
        if (StringUtil.isBlank(uid))
            return 0;

        long count = 0;
        try {
            QueryBuilder<MessageModel, Integer> builder = mDao.queryBuilder();
            builder.where()
                    .eq(MessageModel.UID, uid).and().eq(MessageModel.TYPE, msgType)
                    .and()
                    .eq(MessageModel.DATA3, EMessageStatus.MESSAGE_STATUS_UN_SHOWN.getValue());
            count = builder.countOf();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }

    /**
     * 根据消息类型查询未读数量
     *
     * @param msgType
     * @return
     */
    public long getAllUnReadMsgByType(int msgType) {
        long count = 0;
        try {
            QueryBuilder<MessageModel, Integer> builder = mDao.queryBuilder();
            builder.where().eq(MessageModel.TYPE, msgType)
                    .and()
                    .eq(MessageModel.STATUS, EMessageStatus.MESSAGE_STATUS_UNREAD.getValue());
            count = builder.countOf();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }

//    public long getUnShownMsgByCategory(String uid, int msgCategory){
//    	long totalUnRead = 0;
//    	List<EPushMessageType> msgTypeList = JMiPushMessageUtil.getMessageTypeByCategory(msgCategory);
//    	for (EPushMessageType msgType : msgTypeList){
//    		totalUnRead = totalUnRead + getUnShownByType(uid, msgType.getValue());
//    	}
//    	LogUtil.d("dao", "unshown====totalUnRead ===" + totalUnRead);
//    	return totalUnRead;
//    }

    /**
     * 根据消息类型查询第一条数据
     *
     * @param uid
     * @param msgType
     * @return
     */
    public MessageModel getFristMsgByType(String uid, int msgType) {
        if (StringUtil.isBlank(uid))
            return null;

        try {
            QueryBuilder<MessageModel, Integer> builder = mDao.queryBuilder();
            builder.where()
                    .eq(MessageModel.UID, uid).and().eq(MessageModel.TYPE, msgType);
            builder.orderBy(MessageModel.INSERT_TIME, true);
//			Message message = builder.queryForFirst();

            List<MessageModel> msgList = builder.query();
            if (msgList != null && msgList.size() > 0) {
                return msgList.get(msgList.size() - 1);
            } else {
                return null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


//	public Message getFirstMsgByCategory(String uid,int msgCategory){
//		List<Message> fisrtMsgList = new ArrayList<Message>();
//		List<EPushMessageType> msgTypeList = JMiPushMessageUtil.getMessageTypeByCategory(msgCategory);
//
//		for (EPushMessageType msgType : msgTypeList){
//			Message firstMsg = getFristMsgByType(uid,msgType.getValue());
//			if (firstMsg != null){
//				fisrtMsgList.add(firstMsg);
//			}
//		}
//
//		Collections.sort(fisrtMsgList, new TimeComparator());
//
//		if (fisrtMsgList != null && fisrtMsgList.size() > 0){
//			return fisrtMsgList.get(0);
//		}else{
//			return null;
//		}
//	}

    // 按时间排序
    private class TimeComparator implements Comparator<MessageModel> {

        @Override
        public int compare(MessageModel m1, MessageModel m2) {
            if (m1.getInsertTime() < m2.getInsertTime()) {
                return 1;
            }
            return -1;
        }

    }
}
